package com.soulgame.sms.pay;

import java.util.HashMap;

import mm.purchasesdk.OnPurchaseListener;
import mm.purchasesdk.Purchase;
import mm.purchasesdk.core.PurchaseCode;
import android.app.Activity;

import com.soul.sdk.constants.ResultCode;
import com.soul.sdk.plugin.pay.IPayCallBack;
import com.soul.sdk.plugin.pay.PayParams;
import com.soul.sdk.utils.SGDebug;
import com.soul.sdk.utils.json.KJSONObject;
import com.soulgame.sms.contant.PayType;
import com.soulgame.sms.pay.vo.VoMMPayParams;
import com.soulgame.sms.pay.vo.VoPayParams;

/**
 * @author lch
 * @version Create time：2017-3-15
 * @类说明：移动MM
 */
public class MMPay extends SMSPay {

	private MMPay self;

	private Purchase purchase;

	private VoMMPayParams mVoMMPayParams;
	// 初始化是否完成，初始化完成后才可以进行其它操作，不过是否成功
	public static boolean isInitFinish = false;

	@Override
	public String getPayType() {
		return PayType.MM;
	}
	
	@Override
	public VoPayParams getVoPayParams() {
		return mVoMMPayParams;
	}

	@Override
	public void init(Activity pActivity, KJSONObject pSdkParamsJSON) {
		this.self = this;
		this.mVoMMPayParams = new VoMMPayParams(pSdkParamsJSON);

		this.initMM(pActivity);

	}

	private void initMM(Activity pActivity) {
		try {
			purchase = Purchase.getInstance();

			purchase.setAppInfo(mVoMMPayParams.getAppId(), mVoMMPayParams.getAppKey(), mVoMMPayParams.getSkin());

			purchase.init(pActivity, getListener(null, null));

		} catch (Exception e1) {
			e1.printStackTrace();
			SGDebug.print_e(this, "mm init error = " + e1);
		}
	}

	private OnPurchaseListener getListener(final PayParams pPayParams, final IPayCallBack pPayCallBack) {
		return new OnPurchaseListener() {

			@Override
			public void onInitFinish(String code) {
				// 初始化完成
				isInitFinish = true;
				String result = "初始化结果：" + Purchase.getReason(code);
				SGDebug.v(self, result);

			};

			@Override
			public void onBillingFinish(String code, HashMap<String, Object> arg1) {

				if (PurchaseCode.BILL_ORDER_OK.equalsIgnoreCase(code) || PurchaseCode.AUTH_OK.equalsIgnoreCase(code)
						|| PurchaseCode.WEAK_ORDER_OK.equalsIgnoreCase(code)) {
					// 商品购买成功或者已经购买。 此时会返回商品的paycode，orderID,以及剩余时间(租赁类型商品)
					if (pPayCallBack != null) {
						pPayCallBack.onSuccess(ResultCode.CODE_PAY_SUCCESS, "支付短信发送成功", pPayParams);
					}

					if (arg1 != null) {
						if (SGDebug.isDebug()) {
							// 此次订购的orderID
							String orderID = (String) arg1.get(OnPurchaseListener.ORDERID);
							// 商品的paycode
							String paycode = (String) arg1.get(OnPurchaseListener.PAYCODE);
							// 商品的有效期(仅租赁类型商品有效)
							String leftday = (String) arg1.get(OnPurchaseListener.LEFTDAY);
							// 商品的交易 ID，用户可以根据这个交易ID，查询商品是否已经交易
							String tradeID = (String) arg1.get(OnPurchaseListener.TRADEID);
							String ordertype = (String) arg1.get(OnPurchaseListener.ORDERTYPE);
							//
							SGDebug.d(self, String.format(
									"orderID=%s || paycode=%s || leftday=%s || tradeID=%s || ordertype=%s", orderID, paycode,
									leftday, tradeID, ordertype));
						}
					}

				} else if (PurchaseCode.WEAK_BILL_CANCEL_FAIL.equalsIgnoreCase(code)) {
					// 取消
					if (pPayCallBack != null) {
						pPayCallBack.onFail(ResultCode.CODE_PAY_CANCEL, "支付取消", pPayParams);
					}

				} else {
					// 表示订购失败
					if (pPayCallBack != null) {
						pPayCallBack.onFail(ResultCode.CODE_PAY_FAIL, "支付失败", pPayParams);
					}
				}
			}

			@Override
			public void onQueryFinish(String code, HashMap<String, Object> arg1) {
				// 查询相关

			}

			@Override
			public void onUnsubscribeFinish(String code) {
				// String result = "退订结果：" + Purchase.getReason(code);
			}

			@Override
			public void onBeforeDownload() {

			}

			@Override
			public void onBeforeApply() {

			}

			@Override
			public void onAfterDownload() {

			}

			@Override
			public void onAfterApply() {

			}
		};

	}

	@Override
	public void pay(Activity pActivity, PayParams pPayParams, IPayCallBack pPayCallBack) {

		if (isInitFinish) {
			try {
				// data，本参数是可透传到开发者服务器的自定义数据，长度：弱联网计费点16位以内，强联网计费点64位以内。必须数字和字母。
				String data = pPayParams.getSdkOrderId();
				String paycode = mVoMMPayParams.getPayCode(pPayParams.getProductId());
				// nextCycle, 对于租赁类业务，可以预订下一期租赁周期。
				boolean nextCycle = true;
				// TradeID,（经打印，发现返回的是 null） 调用order()接口返回的交易ID，用于查询交易是否成功
				String tradeid = purchase.order(pActivity, paycode, 1, data, nextCycle, getListener(pPayParams, pPayCallBack));
				// SGDebug.d(self,"pay tradeid="+tradeid);
			} catch (Exception e) {
				if (pPayCallBack != null) {
					pPayCallBack.onFail(ResultCode.CODE_PAY_FAIL, "支付过程发生异常", pPayParams);
				}
				SGDebug.print_w(self, e.toString());
			}

		} else {
			if (pPayCallBack != null) {
				pPayCallBack.onFail(ResultCode.CODE_PAY_FAIL, "MM 初始化尚未完成！", pPayParams);
			}
			
		}
	}

}
